package admin.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
/**
 * @author xf07b1
 * @wechat xf07b1
 * @description
 */
@RestController
@RequestMapping("/api/image")
public class ImageController {

    // 直接在代码中写死图片存储路径
    private static final String UPLOAD_DIR = "./upload/";
    private static final Path FILE_STORAGE_LOCATION = Paths.get(UPLOAD_DIR).toAbsolutePath().normalize();

    // 初始化时创建目录
    public ImageController() {
        try {
            Files.createDirectories(FILE_STORAGE_LOCATION);
        } catch (Exception ex) {
            throw new RuntimeException("无法创建文件存储目录", ex);
        }
    }

    /**
     * 上传图片接口
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        // 生成随机文件名并保留扩展名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFileName != null && originalFileName.contains(".")) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString().replace("-","") + fileExtension;

        try {

            Path targetPath = FILE_STORAGE_LOCATION.resolve(fileName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            return fileName;

        } catch (IOException ex) {
            throw new RuntimeException("文件存储失败: " + ex.getMessage());
        }
    }

    /**
     * 图片预览接口 - 使用OutputStream直接写入响应
     */
    @GetMapping("/download/{fileName}")
    public void getImage(@PathVariable String fileName, HttpServletResponse response) {
        Path filePath = FILE_STORAGE_LOCATION.resolve(fileName).normalize();


        try (InputStream in = Files.newInputStream(filePath);
             OutputStream out = response.getOutputStream()) {

            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            response.setContentType(contentType);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();

        } catch (IOException ex) {
            throw new RuntimeException("文件读取失败: " + ex.getMessage());
        }
    }
}